package com.wzh.yuvwater.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.renderscript.RenderScript;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;


/**
 * Created by wangyt on 2019/6/5
 */
public class BaseActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 1109;
    private String permissionDes;
    private Callback callback;

    private static final String TAG = BaseActivity.class.getSimpleName();
    /**
     * UI操作のためのHandler
     */
    private final Handler mUIHandler = new Handler(Looper.getMainLooper());
    private final Thread mUiThread = mUIHandler.getLooper().getThread();

    public void requestPermission(String permissionDes, Callback callback, @NonNull String... permissions) {
        this.permissionDes = permissionDes;
        this.callback = callback;
        if (checkPermissions(permissions)) {
            if (callback != null) callback.success();
        } else {
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
        }
    }

    public boolean checkPermissions(@NonNull String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return checkSelfPermissions(permissions);
        }
        return true;
    }

    public boolean checkSelfPermissions(@NonNull String... permissions) {
        boolean granted = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                granted = false;
                break;
            }
        }
        return granted;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        boolean granted = true;
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                granted = false;
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                    showPromptDialog();
                } else {
                    if (callback != null) callback.failed();
                }
                break;
            }
        }
        if (granted) {
            if (callback != null) callback.success();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void showPromptDialog() {
        new AlertDialog
                .Builder(this)
                .setTitle("权限申请")
                .setMessage(permissionDes)
                .setCancelable(false)
                .setPositiveButton("去设置", (dialog, which) -> toAppSetting())
                .setNegativeButton("取消", (dialog, which) -> {
                    if (callback != null) callback.failed();
                }).show();
    }

    public void toAppSetting() {
        Intent settingIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        if (Build.VERSION.SDK_INT >= 9) {
            settingIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else {
            settingIntent.setAction(Intent.ACTION_VIEW);
            settingIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            settingIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        settingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(settingIntent);
    }


    /**
     * Shows a {@link Toast} on the UI thread.
     *
     * @param text The message to show
     */
    public void showToast(final String text) {
        runOnUiThread(() ->
                Toast.makeText(this, text, Toast.LENGTH_SHORT).show());
    }

    public interface Callback {
        void success();

        void failed();
    }

    /**
     * UIスレッドでRunnableを実行するためのヘルパーメソッド
     *
     * @param task
     * @param duration
     */
    public final void runOnUiThread(final Runnable task, final long duration) {
        if (task == null) return;
        mUIHandler.removeCallbacks(task);
        if ((duration > 0) || Thread.currentThread() != mUiThread) {
            mUIHandler.postDelayed(task, duration);
        } else {
            try {
                task.run();
            } catch (final Exception e) {
                //Log.w(TAG, e);
            }
        }
    }

    public void sendMessage(Message message) {
        mUIHandler.sendMessage(message);
    }

}
